package com.yz.jdd.module.login.presenter;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.login.view.LoginView;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.request.Request_UserLogin;
import com.yz.jdd.network.response.Response_UserLogin;

import java.util.regex.Pattern;


/**
 * Created by cc on 2017/5/23.
 */

public class LoginPresenter {


    private LoginView loginView;

    private Request_UserLogin request_userLogin;

    public LoginPresenter(LoginView loginView) {
        this.loginView = loginView;

        request_userLogin = new Request_UserLogin();
        initRequest();
    }

    private void initRequest() {

        String networkType = loginView.getNetWorkType();//	N	int		登录网络类型 0-WIFI;1-移动网络
        if (!TextUtils.isEmpty(networkType)) {
            request_userLogin.setNetworkType(networkType);
        }

        //取历史位置信息，同事异步更新一下定位信息
        String lon = loginView.getLon();//	N	string	10	登录经度
        String lat = loginView.getLat();
        //	N	string	10	登录纬度
        request_userLogin.setLat(lat);
        request_userLogin.setLon(lon);

        String type = "21";// Y int app类型：1-pos，2-商家App 20-金多多 21-同福
        request_userLogin.setType(type);
    }

    private void login() {
        loginView.showLoading("正在登录");
        try {
            NetWorkRequset.userLogin(new MySubscriber() {
                @Override
                public void onSuccess(Response_Base response_baseModel) {
                    //返回权限以及user
                    loginView.dismissLoading();
                    Response_UserLogin response = (Response_UserLogin) response_baseModel.getResultObject();
                    if (response != null) {
                        PreferencesUtils.putString(
                                MyApplication.application,
                                BaseConfigs.PREF_USERNAME, response.getUserName());

                        PreferencesUtils.putString(
                                MyApplication.application,
                                BaseConfigs.PREF_SHOPNAME, response.getShopName());

                        PreferencesUtils.putBoolean(MyApplication.application, BaseConfigs
                                .PREF_VERIFICATION_FLAG, response.isVerificationFlag());

                        PreferencesUtils.putString(MyApplication.application, BaseConfigs
                                .STRING_ROUTERCODE, response.getRouterCode());

                        PreferencesUtils.putString(MyApplication.application, BaseConfigs
                                .POS_SUPPLIERCODE, response.getSupplierCode());


                        String sessionId = response.getSessionId();
                        if (!TextUtils.isEmpty(sessionId)) {

                            PreferencesUtils.putString(
                                    MyApplication.application,
                                    BaseConfigs.PREF_SESSIONID, sessionId);
                        }
                        String shopId = response.getShopId();
                        if (!TextUtils.isEmpty(shopId)) {
                            PreferencesUtils.putString(
                                    MyApplication.application,
                                    BaseConfigs.PREF_SHOPID, shopId);
                        }
                        String regionName = response.getRegionName();
                        PreferencesUtils.putString(MyApplication.application,
                                BaseConfigs.STRING_REGIONNAME, regionName);
                        Gson gson = new Gson();
                        if (response.getMenuInfo() != null) {
                            PreferencesUtils.putString(
                                    MyApplication.application,
                                    BaseConfigs.PREF_MENUINFO, gson.toJson(response.getMenuInfo()));
                        }
                        if (response.getHuabeiInfo() != null) {
                            PreferencesUtils.putString(
                                    MyApplication.application,
                                    BaseConfigs.PREFS_STR_EXTINFO, gson.toJson(response.getHuabeiInfo()));
                        }else {
                            PreferencesUtils.putString(
                                    MyApplication.application,
                                    BaseConfigs.PREFS_STR_EXTINFO, "");
                        }

                        String rc = response.getRc();
                        if (!TextUtils.isEmpty(rc)) {

                            PreferencesUtils.putString(
                                    MyApplication.application,
                                    BaseConfigs.STRING_ROUTE_CODE, rc);
                        }

                        loginView.startMainActivity();
                        loginView.close();
                    }


                }

                @Override
                public void onNeedLogin(String msg) {
                    loginView.dismissLoading();
                }

                @Override
                public void onCompleted() {
                    super.onCompleted();
                    loginView.dismissLoading();

                }

                @Override
                public void onFail(Response_Base response_baseModel) {
                    loginView.dismissLoading();
                    if ("101".equals(response_baseModel.getCode())) {
                        loginView.startBindAccountActivity();
                    } else if ("9001".equals(response_baseModel.getCode())) {
                        loginView.startMagicLogin(request_userLogin);

                    } else {
                        loginView.showToastDialog(response_baseModel.getMsg());
                    }
                }
            }, request_userLogin);
        } catch (Exception e) {
            loginView.dismissLoading();
            loginView.showToastDialog("系统异常");
        }
    }

    /**
     * 支付宝联合登录
     */
    public void alipayLogin(String aliUserId) {

        if (TextUtils.isEmpty(aliUserId)) {
//            loginView.showLoading("");
        } else {
            request_userLogin.setAliUserId(aliUserId);
            request_userLogin.setAccount("");
            request_userLogin.setPassword("");
            login();
        }

    }

    /**
     * 正常用户登录
     */
    public void userLogin() {
        //用户登录
        String userName = loginView.getUserName();
        if (checkPhoneNumber(userName)) {
            request_userLogin.setAccount(userName);
        } else {
            return;
        }

//        if (TextUtils.isEmpty(userName)) {
//            loginView.showToast("请输入您的账号");
//            return;
//        } else {
//            //这个地方注释掉了，因为有可能账号变了
////            String phone="^1[34578]\\d{9}$" ;
////            Pattern pattern = Pattern.compile(phone);
////            Matcher matcher = pattern.matcher(userName);
////            if(matcher.matches()) {
//            request_userLogin.setAccount(userName);
////            }else{
////
////                loginView.showToast("请输入正确的账号");
////                return;
////            }
//
//        }
        request_userLogin.setAliUserId("");
        String password = loginView.getPassWord();


        if (TextUtils.isEmpty(password)) {
            loginView.showToast("请输入您的密码");
            return;
        } else {
            if (password.indexOf(" ") != -1 || password.length() < 6 || password.length() > 14) {
                loginView.showToast("密码长度为6-14位英文、数字组合");
                return;
            }
            request_userLogin.setPassword(password);
        }
        //操作modle层执行登录
        login();

    }

    /**
     * 检查手机号码
     *
     * @param phoneNumber 手机号码
     */
    private boolean checkPhoneNumber(String phoneNumber) {
        boolean isPhoneNumber = false;
        if (TextUtils.isEmpty(phoneNumber)) {
            loginView.showToast("请填写手机号");
        } else if (phoneNumber.length() < 11) {
            loginView.showToast("请填写有效的手机号");
        } else if (!Pattern.matches("^(0|86|17951)?(1[0-9])[0-9]{9}$", phoneNumber)) {
            loginView.showToast("请填写有效的手机号");
        } else {
            isPhoneNumber = true;
        }
        return isPhoneNumber;
    }
}
